package com.aoxin.service.impl.client;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.joda.time.DateTime;
import org.joda.time.Duration;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.aoxin.mapper.client.EpOrderServiceDao;
import com.aoxin.mapper.course.webCourse.SlfChildrenMapper;
import com.aoxin.mapper.opm.SlfUserMapper;
import com.aoxin.model.course.SlfChildren;
import com.aoxin.model.opm.SlfUser;
import com.aoxin.service.inter.client.EpOrderService;
import com.aoxin.util.ErrorUtil;
import com.aoxin.util.ThreadLocalUtil;

@Service("EpOrderService")
public class EpOrderServiceImp implements EpOrderService {
	@Autowired
	private EpOrderServiceDao epOrderServiceDao;
	@Autowired
	private SlfUserMapper slfUserMapper;
	@Autowired
	SlfChildrenMapper slfChildrenMapper;
	

	/**
	 * 查询课程表最近一条记录(根据孩子id)
	 * 
	 * @return
	 */
	@Override
	public List<Map<String, Object>> checkLimitCourse(String startDate) {
		Integer childrenId = ThreadLocalUtil.getChildren().getChildrenId();
		Integer schoolId = ThreadLocalUtil.getChildren().getSchoolId();
		//TODO 需要添加时间条件
		//条件时间查询
		Map<String, Object> stringObjectMap = epOrderServiceDao.checkLimitCourse(childrenId,startDate);
		 String schoolName= ThreadLocalUtil.getChildren().getSchoolName();
		
		// 日期格式解析
		DateTimeFormatter format = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
		if (stringObjectMap != null) {
			// 已经进行中的B类课程
			// 如果判断时间 如果大于4小时    
			//TODO 需要查询多条线最近课程 top  在进行数据测试的时候发现排出的课程出现两个在同一时间段，对应同一个用户 分别是2人最低开班 和一人最低开班，期望时间
			//为周一 10-11点 11-12点
			List<Map<String, Object>> latestCourse = epOrderServiceDao.queryLatestCourse(childrenId,startDate);
			List<Map<String,Object>>  courseDataList=new ArrayList<Map<String,Object>>();
			
			
			for (int i = 0,b=latestCourse.size(); i <b; i++) {
				// 排表时间
				DateTime t2 = DateTime.parse(latestCourse.get(i).get("employ_time").toString(), format);
				// 如果小于或者等于4小时
				DateTime t1 = new DateTime().plusHours(4);
				Map<String, Object> courseData = epOrderServiceDao
						.queryCourseDetails(Integer.parseInt(latestCourse.get(i).get("course_id").toString()), schoolId);
				
				courseData.put("id", latestCourse.get(i).get("id"));	
				//查询学校课程包ID
				Map<String,Object> schoolCoursetoPageData=epOrderServiceDao.querySchoolCoursePageId(Integer.parseInt(courseData.get("school_course_id").toString()), schoolId);
				courseData.put("school_course_page_id",schoolCoursetoPageData.get("school_course_page_id"));
				if (Integer.parseInt(latestCourse.get(i).get("Flag").toString()) == 2) {
					// 2 为排队中
					courseData.put("courseSate", "2");
				} else {
					if (t2.isAfter(t1)||!"".equals(startDate)) {
						//startDate 选择时间 默认为大于4小时
						// 大于4个小时 3按钮为取消
						courseData.put("courseSate", "3");
					} else {
						// 小于4个小时 即将开始
						courseData.put("courseSate", "4");
					}
				}
				Duration duration=new Duration(t1,t2);
				Long countDown =duration.getStandardSeconds();
				courseData.put("countDown", countDown);
				//1 为课程
				courseData.put("dataType", "1");
				if(courseData.get("sales_start_date")!=null && courseData.get("sales_start_date")!=""){
					String  str=courseData.get("sales_start_date").toString();
					courseData.put("sales_start_date", new DateTime(str).toString("yyyy-MM-dd")); 
				}
				if(courseData.get("sales_end_date")!=null && courseData.get("sales_end_date")!=""){
					String  str=courseData.get("sales_end_date").toString();
					courseData.put("sales_end_date", new DateTime(str).toString("yyyy-MM-dd")); 
				}
				Integer classRoomId=Integer.parseInt(stringObjectMap.get("classrooom_id").toString());
				String  classRoomName=epOrderServiceDao.queryClassRoom(classRoomId);
				courseData.put("classRoomName", classRoomName);
				
				courseData.put("schoolName", schoolName);	
				String startTime=t2.minusHours(1).toString("yyyy-MM-dd hh:mm:ss");
				String endTime=t2.toString("hh:mm:ss");
				courseData.put("courseTime", startTime+"-"+endTime);
				courseDataList.add(courseData);
			}
			return courseDataList;
		} else {
			
			// 判断是否有预约的的C类课程并且未开课
			// 如果有预约的C类课程
			// 查询B类最近一条 有空余的教师的课程ID (根据教室id和结束时间)
			// 根据课程ID查询课程信息
			// 没有预约的C类课程
			Integer integer = epOrderServiceDao.queryIsOrderC(childrenId,startDate);
			Integer isVIP=ThreadLocalUtil.getUser().getFlag();
			if (integer > 0 ) {
				// 有即将进行中的C类课程
				// slf_class_course_number 中最近一堂课程人数为负数的信息 
				Map<String,Object> vacancyCourseData=epOrderServiceDao.queryVacancyCourseData();
				// 查询有空余位置教室信息  
				List<Map<String, Object>> freePosition = epOrderServiceDao.queryRoomIdAndEndTime(startDate);
				if(vacancyCourseData==null || vacancyCourseData.size()==0){
					/**
					 * 业务：当 slf_class_course_number 中没有任何一堂课是缺人时，查询slf_classroom_employ 中有没排班是人数不够的
					 * 没有 返回课程包 有就返回最近一个课程
					 */
					
					// class_course_number 为空  原来的流程
					if ( freePosition != null &&  freePosition.size() > 0) {
						/**
						 * 取出的课程信息时需要判断在 slf_class_course_number 中的人数为多少 
						 */
						
						Map<String,Object>	 resultMapCourse=new HashMap<String,Object>();
						Integer courserId=0;
						Integer vacancyNumber=0;
						Integer classRoomId=0;
						for (int i = 0,b=freePosition.size(); i < b; i++) {
							 classRoomId=Integer.parseInt(freePosition.get(i).get("classroom_id").toString());
							//排除掉 该堂课已满的教室
							resultMapCourse = epOrderServiceDao.queryFreePositionCourse(classRoomId,freePosition.get(i).get("employ_time").toString());
							courserId=Integer.parseInt(resultMapCourse.get("course_id").toString());  
							//TODO epOrderServiceDao.queryVacancyCourseNumber(classcourserId,classRoomId,resultMapCourse.get("employ_time").toString())
							//为空会抛异常
							Integer vacancyCourseNumber	=epOrderServiceDao.queryVacancyCourseNumber(courserId,classRoomId,resultMapCourse.get("employ_time").toString())==null?0:epOrderServiceDao.queryVacancyCourseNumber(courserId,classRoomId,resultMapCourse.get("employ_time").toString());
							Integer classVacancyCourseNumber=Integer.parseInt(freePosition.get(i).get("employ_num").toString()); 
							if(classVacancyCourseNumber>vacancyCourseNumber){
								vacancyNumber=(classVacancyCourseNumber-vacancyCourseNumber);
								break;
							}
						}
							// 有空余位置 获取最近的一个课程信息 
							// 查询课程详情
							Map<String, Object> courseData = epOrderServiceDao.queryCourseDetails(courserId, schoolId);
							courseData.put("freePosition", vacancyNumber);
							// 日期格式化   开课时间
							DateTime t2 = DateTime.parse(resultMapCourse.get("employ_time").toString(), format).minusHours(1);
							courseData=getCourseData(courseData,t2,schoolId);
							courseData.put("classRoomId", classRoomId);
							String  classRoomName=epOrderServiceDao.queryClassRoom(classRoomId);
							courseData.put("classRoomName", classRoomName);
							courseData.put("schoolName", schoolName);
							List<Map<String,Object>>  courseDataList=new ArrayList<Map<String,Object>>();
							courseDataList.add(courseData);
							return courseDataList;
						} else {
							// 无空余 返回一个热门课程包
							Map<String,Object> coursePage=epOrderServiceDao.queryHotCoursePage(schoolId, childrenId);
							//课程包2
							coursePage.put("dataType", "2");
							if(coursePage.get("sales_start_date")!=null && coursePage.get("sales_start_date")!=""){
								String  str=coursePage.get("sales_start_date").toString();
								coursePage.put("sales_start_date", new DateTime(str).toString("yyyy-MM-dd")); 
							}
							if(coursePage.get("sales_end_date")!=null && coursePage.get("sales_end_date")!=""){
								String  str=coursePage.get("sales_end_date").toString();
								coursePage.put("sales_end_date", new DateTime(str).toString("yyyy-MM-dd")); 
							}
							coursePage.put("schoolName", schoolName);
							
							List<Map<String,Object>>  courseDataList=new ArrayList<Map<String,Object>>();
							courseDataList.add(coursePage);
							return courseDataList;
							
						}
					
				}else{
					if(freePosition.size()==0||freePosition==null){
						
						// 空余教室为空  取class_course_number 
					Integer courserId=Integer.parseInt(vacancyCourseData.get("course_id").toString());
						
					// 查询课程详情
					Map<String, Object> courseData = epOrderServiceDao.queryCourseDetails(courserId, schoolId);
					//TODO   不应该用 freePosition 去空位人数     应该是vacancyCourseData
					courseData.put("freePosition",-Integer.parseInt(vacancyCourseData.get("vacancy").toString()));
					// 日期格式化   开课时间
					DateTime t2 = DateTime.parse(vacancyCourseData.get("end_time").toString(), format).minusHours(1);
					courseData.put("classRoomId", vacancyCourseData.get("classroom_id"));
					courseData=getCourseData(courseData,t2,schoolId);
					courseData.put("schoolName", schoolName);
					Integer classRoomId=Integer.parseInt( vacancyCourseData.get("classroom_id").toString());
					String  classRoomName=epOrderServiceDao.queryClassRoom(classRoomId);
					courseData.put("classRoomName", classRoomName);
					
					
					List<Map<String,Object>>  courseDataList=new ArrayList<Map<String,Object>>();
					courseDataList.add(courseData);
					return courseDataList;
					}else{
						/**
						 * 查询 未满员的课程数据 
						 */
						Map<String,Object>	 resultMapCourse=new HashMap<String,Object>();
						Integer classcourserId=0;
						Integer vacancyNumber=0;
						Integer classRoomId=0;
						for (int i = 0,b=freePosition.size(); i < b; i++) {
							 classRoomId=Integer.parseInt(freePosition.get(i).get("classroom_id").toString());
							//排除掉 该堂课已满的教室
							resultMapCourse = epOrderServiceDao.queryFreePositionCourse(classRoomId,freePosition.get(i).get("employ_time").toString());
							classcourserId=Integer.parseInt(resultMapCourse.get("course_id").toString());  
							//TODO epOrderServiceDao.queryVacancyCourseNumber(classcourserId,classRoomId,resultMapCourse.get("employ_time").toString())
							//为空会抛异常
							Integer vacancyCourseNumber	=epOrderServiceDao.queryVacancyCourseNumber(classcourserId,classRoomId,resultMapCourse.get("employ_time").toString())==null?0:epOrderServiceDao.queryVacancyCourseNumber(classcourserId,classRoomId,resultMapCourse.get("employ_time").toString());
							Integer classVacancyCourseNumber=Integer.parseInt(freePosition.get(i).get("employ_num").toString()); 
							if(classVacancyCourseNumber>vacancyCourseNumber){
								vacancyNumber=(classVacancyCourseNumber-vacancyCourseNumber);
								break;
							}
						}
						//教室结束时间
						DateTime t3 = DateTime.parse(resultMapCourse.get("employ_time").toString(), format);
						//class_number
						DateTime t4 = DateTime.parse(vacancyCourseData.get("end_time").toString(), format);
						
						if(t4.isBefore(t3)){
							//class_number 时间在前
							// 空余教室为空  取class_course_number 
							Integer courserId=Integer.parseInt(vacancyCourseData.get("course_id").toString());
							// 查询课程详情
							Map<String, Object> courseData = epOrderServiceDao.queryCourseDetails(courserId, schoolId);
							courseData.put("freePosition",-Integer.parseInt(vacancyCourseData.get("vacancy").toString()));
							// 日期格式化   开课时间
							DateTime t2 = DateTime.parse(vacancyCourseData.get("end_time").toString(), format).minusHours(1);
							courseData=getCourseData(courseData,t2,schoolId);
							courseData.put("classRoomId", vacancyCourseData.get("classroom_id"));
							courseData.put("schoolName", schoolName);
							String  classRoomName=epOrderServiceDao.queryClassRoom(classRoomId);
							courseData.put("classRoomName", classRoomName);
							
							List<Map<String,Object>>  courseDataList=new ArrayList<Map<String,Object>>();
							courseDataList.add(courseData);
							return courseDataList;
						}else{
							//教室那边的时间在前
						// 有空余位置 获取最近的一个课程信息 
						Integer courserId=Integer.parseInt(resultMapCourse.get("course_id").toString());  
						// 查询课程详情
						Map<String, Object> courseData = epOrderServiceDao.queryCourseDetails(courserId, schoolId);
						courseData.put("freePosition",vacancyNumber);
						// 日期格式化   开课时间
						DateTime t2 = DateTime.parse(resultMapCourse.get("employ_time").toString(), format).minusHours(1);
						courseData=getCourseData(courseData,t2,schoolId);
						courseData.put("classRoomId", classRoomId);
						String  classRoomName=epOrderServiceDao.queryClassRoom(classRoomId);
						courseData.put("classRoomName", classRoomName);
						courseData.put("schoolName", schoolName);
						List<Map<String,Object>>  courseDataList=new ArrayList<Map<String,Object>>();
						courseDataList.add(courseData);
						return courseDataList;
						}
					} 
				}
			} else {
				// 无进行中的C类课程 返回热门课程包
				 Map<String,Object> coursePage=epOrderServiceDao.queryHotCoursePage(schoolId, childrenId);
				coursePage.put("dataType", "2");
				coursePage.put("schoolName", schoolName);
				List<Map<String,Object>>  courseDataList=new ArrayList<Map<String,Object>>();
				courseDataList.add(coursePage);
				return courseDataList;
			}
		}
	}

	/**
	 * 修改课程表状态(取消,排队中,即将开始上课)
	 *   
	 * @param state
	 * @param id  表主键id 
	 * @return
	 */
	@Override
	@Transactional
	public Integer updateState(String state, Integer id) {
		//state 3 取消
		Integer userId = ThreadLocalUtil.getUser().getUserId();
		Integer childrenId = ThreadLocalUtil.getChildren().getChildrenId();
		Integer schoolId = ThreadLocalUtil.getChildren().getSchoolId();
		Map<String,Object> userCourseConditionData=epOrderServiceDao.queryCourseConditiion(id);
		Integer employFlag=Integer.parseInt(userCourseConditionData.get("employ_flag").toString()); 
		SlfUser slfUser = this.slfUserMapper.selectByPrimaryKey(userId);
		DateTimeFormatter format = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
		//获取课程id
		//更新我的课程
		//epOrderServiceDao.updateMyCourse(schoolCourseId,childrenId,Integer.parseInt(state));
		/**
		 * 点击取消
		 * 判断是否为散户-- 既我的课程包中是否有该课程包 无则为散户退钱处理，同时删除课程数据 同时往slf_class_course_number表中添加一条人数为-1的数据
		 * 				 我的课程包中有该课程包既为正式用户，进行补课状态，修改 slf_user_course_condition 该用户该堂课程状态
		 * 				 同时往slf_class_course_number表中添加一条人数为-1的数据
		 */
		Integer schoolCoursePageId=Integer.parseInt(userCourseConditionData.get("course_backage_id").toString());
		Integer myCoursePageAmount=epOrderServiceDao.queryCoursePageAmountInMyCoursePage(schoolCoursePageId,childrenId);
			if(myCoursePageAmount>0){
				//購買了該課程包
				// 往number 表中添加数据
				//往slf_class_course_number表中添加一条人数为-1的数据
				epOrderServiceDao.insertCourseNumberData(id,1);
				//修改课程状态
				return 	epOrderServiceDao.updateState(id, childrenId, Integer.parseInt(state));
			}else{
				Integer flag=0;
				if(employFlag==1){
					// 1 为C 
					flag=employFlag;
					
				}else if(employFlag==0){
					//0 为B
					flag=employFlag;
				}
				// 為購買該課程包為散戶 直接退錢  删除 排表课程数据， 新添 number 表数据 
				epOrderServiceDao.insertCourseNumberData(id,flag);
				Integer courseId=Integer.parseInt( userCourseConditionData.get("course_id").toString());
				//  查询课程价钱 
				Map<String, Object> courseData=	 epOrderServiceDao.queryCourseDetails(courseId, schoolId);
				 SlfChildren slfchildren= slfChildrenMapper.getAChildren(childrenId);
				if(slfchildren.getVipLv()!=1){
					
					BigDecimal userLfb =new BigDecimal(slfUser.getLfb().toString());
					
					DateTime t1 = DateTime.parse(userCourseConditionData.get("employ_time").toString(), format);
					Duration duration=new Duration(new DateTime(),t1);
					BigDecimal lastMoney =new BigDecimal(courseData.get("price").toString());
					
					if (courseData.get("discount_price") != null || courseData.get("discount_price") != "") {
						// 有折扣
						lastMoney =new BigDecimal(courseData.get("discount_price").toString());
					}
					Long differenceValueMinutes=duration.getStandardMinutes();
					
					if(differenceValueMinutes<(4*60)&&differenceValueMinutes>(3*60)){
						
						Long Minutes=(4*60)-differenceValueMinutes;
						
						BigDecimal deductionMinutes=lastMoney.divide(new BigDecimal(60));
						BigDecimal returnMoney= deductionMinutes.multiply(new BigDecimal(Minutes));
						lastMoney=lastMoney.subtract(returnMoney);
					}else if(differenceValueMinutes<3*60){
						lastMoney=new BigDecimal(0);
					}
					// 返还立方币
					BigDecimal bestmoney=userLfb.add(lastMoney);
					epOrderServiceDao.updateUserLfb(bestmoney.doubleValue(), userId);
				}
				// 删除课程数据
				return 	epOrderServiceDao.deleteCourseConditionId(id);
			}
	}

	/**
	 * 根据B类课程ID插入到课程表
	 * 
	 * @param courseId
	 * @return
	 */
	@Override
	@Transactional
	public Integer addEPOrder(Integer courseId) {
		Integer childrenId = ThreadLocalUtil.getChildren().getChildrenId();
		Integer schoolId = ThreadLocalUtil.getChildren().getSchoolId();
		Integer userId = ThreadLocalUtil.getUser().getUserId();
		SlfUser slfUser = this.slfUserMapper.selectByPrimaryKey(userId);
		// 扣除用户立方币
		BigDecimal  userLfb =new BigDecimal(slfUser.getLfb().toString());
		String userName=ThreadLocalUtil.getUser().getName();
		Integer  schoolCoursePageId	=epOrderServiceDao.queryCoursBackageIdByCourseId(courseId);
		Integer myCoursePageAmount=epOrderServiceDao.queryCoursePageAmountInMyCoursePage(schoolCoursePageId,childrenId);
		if(myCoursePageAmount>0){
			//已购买过课程包 无法排队
			throw new IllegalArgumentException("已购买过该课程对应课程包，无法再次参加该类课程！");
		}
		
		//
		Map<String, Object> courseData = epOrderServiceDao.queryCourseDetails(courseId, schoolId);
		BigDecimal lastMoney =new BigDecimal(courseData.get("price").toString());
		/**
		 * 普通用户扣钱
		 */
		 SlfChildren slfchildren= slfChildrenMapper.getAChildren(childrenId);
		if(slfchildren.getVipLv()!=1){
			if (courseData.get("discount_price") != null || courseData.get("discount_price") != "") {
				// 有折扣
				lastMoney =new BigDecimal(courseData.get("discount_price").toString());
			}
			//boolean flag = userLfb > lastMoney ? true : false;
			//-1 用户lfb小于价格
			boolean flag = userLfb.compareTo(lastMoney)==-1?false:true;
			if (!flag) {
				throw new IllegalArgumentException(ErrorUtil.NOT_ENOUGH_BALANCE);
			}
			// 扣除立方币
			BigDecimal bestmoney=userLfb.subtract(lastMoney);
			epOrderServiceDao.updateUserLfb(bestmoney.doubleValue(), userId);
		}
		
		
		//往我的课程中添加数据
		epOrderServiceDao.insertDataToMyCourse(childrenId, userId, userName, courseId, schoolId);
		 // 添加number 数据
		epOrderServiceDao.insertCourseNumberByCourseId(courseId,childrenId);
		
		return epOrderServiceDao.addEPOrder(childrenId, courseId,schoolId,ThreadLocalUtil.getChildren().getName());
	}
	/**
	 *   获取课程数据
	 * @param courseData  返回map数据
	 * @param t2  开课时间
	 * @param schoolId  学校ID
	 * @return
	 */
	private Map<String,Object> getCourseData(Map<String,Object> courseData,DateTime t2,Integer schoolId){
		
			Duration duration=new Duration(new DateTime(),t2);
			Long countDown =duration.getStandardSeconds();
			String shcoolCourseId =courseData.get("school_course_id").toString();
			//查询学校课程包ID
			Map<String,Object> schoolCoursetoPageData=epOrderServiceDao.querySchoolCoursePageId(Integer.parseInt(shcoolCourseId), schoolId);
			courseData.put("countDown", countDown);
			courseData.put("school_course_page_id",schoolCoursetoPageData.get("school_course_page_id"));
			//1 立即排队
			courseData.put("courseSate", "1");
			courseData.put("dataType", "1");
			if(courseData.get("sales_start_date")!=null && courseData.get("sales_start_date")!=""){
				String  str=courseData.get("sales_start_date").toString();
				courseData.put("sales_start_date", new DateTime(str).toString("yyyy-MM-dd")); 
			}
			if(courseData.get("sales_end_date")!=null && courseData.get("sales_end_date")!=""){
				String  str=courseData.get("sales_end_date").toString();
				courseData.put("sales_end_date", new DateTime(str).toString("yyyy-MM-dd")); 
			}
			
			return courseData;
		
	}
	
	
	
	
	
}
